﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;
using LapvComponent;
using LapvBussiness;
using LapvWebComponent;

namespace Lapv.page
{
    public partial class NewsAdd : System.Web.UI.Page
    {
        int newsid = 0;
        public int StatusNews = 0;
        private static readonly ILog log = LogManager.GetLogger(typeof(NewsAdd).Name);
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["newsid"] != null)
                int.TryParse(Request.Params["newsid"], out newsid);
            string urlReturn = this.Request.RawUrl.ToString();
            ProviderAdmin.CheckAuthen(urlReturn, 3);
            if (Page.IsPostBack) return;
          
            BindCate();
            if (newsid > 0)
                LoadData(newsid);
            
        }
        void LoadData(int id)
        {
           
            try
            {
               
                if (id > 0)
                {
                    using (lapvwebEntities db = new lapvwebEntities())
                    {
                        news obj = db.news.Include("news_category").Where(ec => ec.id == id).FirstOrDefault();
                        if (obj != null)
                        {
                            ddlCate.SelectedValue = obj.news_category.id.ToString();
                            txtTitle.Text = obj.title;
                            txtContent.Text = obj.content;
                            if(obj.viewcount>0)
                            txtViewCount.Text = obj.viewcount.ToString();
                            rblAllowDelete.SelectedValue = obj.allowdelete.ToString();
                            rblStatus.Value= obj.status.ToString();                           
                            if (obj.status == 2 && obj.starttimeup!= DateTime.MinValue)
                            {
                                StatusNews = 2;
                                txtCLock.Value = obj.starttimeup.ToString("dd/MM/yyyy");
                                string tt = obj.starttimeup.ToString("tt");
                                if (tt == "PM")
                                    txtHour.Text = (int.Parse(obj.starttimeup.ToString("hh")) + 12).ToString();
                                else
                                    txtHour.Text = obj.starttimeup.ToString("hh");
                                txtMinute.Text = obj.starttimeup.ToString("mm");
                            }
                            txtImage.Text = obj.image;
                            txtShortDes.Text = obj.shortdescription;
                            rblAllowDelete.SelectedValue = obj.allowdelete.ToString();
                        }
                        else
                        {
                            ((Lapv)this.Master).MessageInfomational = "Không có dữ liệu";
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + "--" + ex.Source + "--" + ex.InnerException);
                ((Lapv)this.Master).MessageError = "Đã xảy ra lỗi. " + ex.Message;
                
            }
            
        }
        protected void Submit(object sender, EventArgs e)
        {
            string msg = "";
            string actiontype = "";
            try
            {
                DateTime dt = DateTime.Now;
                string st = txtCLock.Value.Trim();
                if (!string.IsNullOrEmpty(st) && rblStatus.Value=="2")
                {
                    string[] arr = st.Split('/');
                    if (arr.Length == 3)
                    {
                        try
                        {
                            dt = new DateTime(int.Parse(arr[2]), int.Parse(arr[1]), int.Parse(arr[0]));
                        }
                        catch (Exception)
                        {
                        }
                        int hour = 0;
                        string hr = txtHour.Text.Trim();
                        if (!string.IsNullOrEmpty(hr))
                            int.TryParse(hr, out hour);
                        if (!(hour >= 0 && hour < 60))
                        {
                            ((Lapv)this.Master).MessageError = "Giờ không hợp lệ";
                            return;
                        }
                        int minute = 0;
                        string mt = txtMinute.Text.Trim();
                        if (!string.IsNullOrEmpty(mt))
                            int.TryParse(mt, out minute);
                        if (!(minute >= 0 && minute < 60))
                        {
                            ((Lapv)this.Master).MessageError = "Phút không hợp lệ";
                            return;
                        }
                        dt = dt.AddHours(hour).AddMinutes(minute);
                    }
                }
                int cateid = -1;
                sbyte status = -1;
                int viewcount=0;
                bool isdelete = false;
                if (rblStatus.Value != null && rblStatus.Value != "")
                    status = sbyte.Parse(rblStatus.Value.ToString());
                if (status > -1)
                    Session["statusid"] = status;
                if(!string.IsNullOrEmpty(txtViewCount.Text))
                    viewcount=int.Parse(txtViewCount.Text);
                if (ddlCate.SelectedValue != null && ddlCate.SelectedValue != "")
                    cateid = int.Parse(ddlCate.SelectedValue);
                if (cateid > 0)
                    Session["cateid"] = cateid;
                if (rblAllowDelete.SelectedValue != null && rblAllowDelete.SelectedValue != "")
                    isdelete = bool.Parse(rblAllowDelete.SelectedValue);
                
                if (newsid > 0)
                {
                    actiontype = "NEWS_EDIT";
                    using (lapvwebEntities db = new lapvwebEntities())
                    {
                        news old = db.news.Include("news_category").Where(ec => ec.id == newsid).FirstOrDefault();
                        if (old != null)
                        {
                            old.news_categoryReference.EntityKey = new System.Data.EntityKey("lapvEntities.news_category", "id", cateid);
                            old.title = txtTitle.Text;
                            old.content = txtContent.Text;
                            old.status = status;
                            old.image = txtImage.Text;
                            old.shortdescription = txtShortDes.Text;
                            if (status == 2)
                                old.starttimeup = dt;
                            else
                                old.starttimeup = DateTime.MinValue;
                            if (viewcount > 0)
                                old.viewcount = viewcount;
                            old.allowdelete=isdelete;
                            db.ApplyCurrentValues(old.EntityKey.EntitySetName, old);
                            db.SaveChanges();
                            msg = "Sửa tin thành công! Mã tin: "+old.id;
                            
                        }
                        else
                        {
                            ((Lapv)this.Master).MessageError = "Không tồn tại mã tin này";
                            msg = "Sửa tin bị lỗi do không tồn tại mã tin: "+newsid;
                        }

                    }
                }
                else
                {
                    actiontype = "NEWS_EDIT";
                    using (lapvwebEntities db = new lapvwebEntities())
                    {
                        news newsadd = new news();
                        newsadd.news_categoryReference.EntityKey = new System.Data.EntityKey("lapvEntities.news_category", "id", cateid);
                        newsadd.title = txtTitle.Text;
                        newsadd.content = txtContent.Text;
                        newsadd.shortdescription = txtShortDes.Text;
                        newsadd.image = txtImage.Text;
                        newsadd.status = status;
                        newsadd.allowdelete = isdelete;
                        if (viewcount > 0)
                            newsadd.viewcount = viewcount;
                        if (status == 2)
                        {
                            newsadd.starttimeup = dt;
                        }
                        else
                            newsadd.starttimeup = DateTime.MinValue;
                        newsadd.datecreate = DateTime.Now;
                        db.AddTonews(newsadd);
                        db.SaveChanges();
                        msg = "Thêm tin thành công. Mã tin: "+newsadd.id;
                    }
                    

                }
                Response.Redirect("NewsManager.aspx",false);

            }
            catch (Exception ex)
            {
                if (newsid > 0)
                    msg = "Sửa tin tức bị lỗi. Mã tin: "+newsid+". Do "+ex.Message;
                else
                    msg = "Thêm tin tức bị lỗi. Do "+ex.Message;
                log.Error(ex.Message + "--" + ex.Source + "--" + ex.InnerException);
                ((Lapv)this.Master).MessageError = "Đã xảy ra lỗi. " + ex.Message;
            }
            try
            {
                int uid = 0;
                string uname = string.Empty;
                uid = ProviderAdmin.GetUsserId();
                if (Session["UserName"] != null)
                    uname = Session["UserName"].ToString();
                ProviderAdmin.AddLog(uid, uname, msg, string.Empty, actiontype);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
            }
 
        }
        void BindCate()
        {
            try
            {
                List<news_category> lst = Provider.GetListNewsCate();
                if (lst != null && lst.Count > 0)
                {
                    ddlCate.DataSource = lst;
                    ddlCate.DataTextField = "name";
                    ddlCate.DataValueField= "id";
                    ddlCate.DataBind();
                    ddlCate.Items.Insert(0, new ListItem("---Chọn loại tin---", "0"));
                }
            }
            catch (Exception ex)
            {

                log.Error(ex.Message +"--"+ex.Source+"--"+ex.InnerException);
                ((Lapv)this.Master).MessageError = "Đã xảy ra lỗi. " + ex.Message;
            }
        }
        protected void Cancel(object sender, EventArgs e)
        { 
        }
    }
}
